package com.erlinyou.im.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.erlinyou.im.web.controller.base.JsonUtil;
import com.erlinyou.im.web.controller.base.ResultCode;
import com.erlinyou.im.web.controller.base.ResultJsonBuild;
import com.erlinyou.im.web.controller.base.SiteUtil;


/**
 * 参数验证拦截
 * @author xingdongyang
 *
 */
public class LoginInterceptor implements HandlerInterceptor{
	private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	public String[] allowUrls;

	
	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Expose-Headers", "xAuthToken");;
		
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		if(!checkCurrentURL(request,requestUrl)){
			boolean isLogin = SiteUtil.isLogin(request);
			if(!isLogin){
				response.getWriter().write(JsonUtil.ObjectToJson(ResultJsonBuild.buildObj(ResultCode.LOGIN_NOT)));
			}
			return isLogin;
		}else{
			return true;
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}
	
	private boolean checkCurrentURL(HttpServletRequest request,String requestUrl){
		//String ctx = request.getContextPath();
		if(requestUrl.equals("/") || requestUrl.startsWith("/?type=")){
			return true;
		}else if(null != allowUrls && allowUrls.length>=1){
			for(String url : allowUrls) {  
				if(requestUrl.contains(url)) {
					return true;  
				}  
			}
		}
		return false;
	}

}